package cn.edu.zut.internship.service.impl.sys;


import cn.edu.zut.internship.bean.sys.Result;
import cn.edu.zut.internship.entity.AuthSysMenu;
import cn.edu.zut.internship.entity.AuthSysPermission;
import cn.edu.zut.internship.entity.AuthSysRole;
import cn.edu.zut.internship.iservice.sys.IMenuService;
import cn.edu.zut.internship.iservice.sys.IRoleService;
import cn.edu.zut.internship.mapper.sys.AuthSysPermissionMapper;
import cn.edu.zut.internship.mapper.sys.AuthSysRoleMapper;
import cn.edu.zut.internship.utils.PrimaryKeyUtil;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

@Service
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private AuthSysRoleMapper roleMapper;
    @Autowired
    private IMenuService menuService;
    @Autowired
    private AuthSysPermissionMapper permissionMapper;
    @Autowired
    PrimaryKeyUtil primaryKeyUtil;

    @Override
    public List<AuthSysRole> search(String roleName) {
        if(roleName != null && ("null".equalsIgnoreCase(roleName)||"".equals(roleName))){
            roleName = null;
        }
        List<AuthSysRole> roleList = this.roleMapper.selectByName(roleName);
        return roleList;
    }

    @Override
    public AuthSysRole findById(Long rlId) {
        return this.roleMapper.selectByPrimaryKey(rlId);
    }

    @Override
    public Result add(Map role) {


//        this.roleMapper.insertSelective(role);
//        // 判断是否有相关权限需要插入，如果有，就同步添加
//        List<AuthSysMenu> menus = role.getRoutes();
//        if(menus != null && menus.size()>0){
//            for(AuthSysMenu menu:menus){
//                AuthSysMenu mn = this.menuService.findById(menu.getId());
//                if(mn.getParentId() != null && mn.getParentId() > 0) {
//                    this.roleMapper.assignMenu(role.getRlId(), menu);
//                }
//            }
//        }
//        return role;
        Result result = new Result();
        Long roleId = primaryKeyUtil.generatePrimaryKey("sys_role");
        role.put("roleId",roleId);
        roleMapper.insertSelective(role);
        //为此角色绑定菜单权限
        List<Map> menus = (List<Map>) role.get("routes");
        if(!CollectionUtils.isEmpty(menus)){
            for(Map menu:menus){
                    Long menuId;
                if(menu.get("id") instanceof Integer){
                    Integer menuIdInt = (Integer) menu.get("id");
                    menuId = new Long(menuIdInt);
                }else{
                    menuId = (Long) menu.get("id");
                }
                roleMapper.assignMenu(roleId,menuId);
            }
        }
        result.getBean().put("roleId",roleId);
        return result;
    }

    @Override
    public void deleteRole(Map params) {
        Long roleId = (Long) params.get("roleId");
        // 删除角色的菜单关联信息
        this.roleMapper.unassignMenus(roleId);
        //删除角色
        this.roleMapper.deleteByPrimaryKey(roleId);
    }

    @Override
    public void update(Map role) {
//        // 调用Mapper维护角色的基本信息
//        this.roleMapper.updateByPrimaryKey(role);
//        // 删除角色的旧menu（路由信息）
//        this.roleMapper.unassignMenus(rlId);
//        // 获取角色新拥有的路由s
//        List<AuthSysMenu> menus = role.getRoutes();
//        AuthSysMenu parentMenu = null;
//        if(menus != null && menus.size()>0){
//            // 循环的将路由信息分配给角色（给角色分配新的路由信息）
//            for(AuthSysMenu menu:menus){
//                if(!this.roleHasMenu(role.getRlId(), menu.getId())) {
//                    this.roleMapper.assignMenu(role.getRlId(), menu);
//                }
//                parentMenu = this.menuService.findParentMenu(menu.getId());
//                if(parentMenu != null && !this.roleHasMenu(role.getRlId(), parentMenu.getId())){
//                    this.roleMapper.assignMenu(role.getRlId(), parentMenu);
//                }
//            }
//        }
        //更新角色信息
        roleMapper.updateByPrimaryKey(role);
        //删除旧的角色路由菜单绑定关系
        Long roleId;
        if(role.get("sysRoleId") instanceof Integer){
            roleId = new Long((Integer)role.get("sysRoleId"));
        }else{
            roleId = (Long) role.get("sysRoleId");
        }
        roleMapper.unassignMenus(roleId);
        //给角色绑定新的路由菜单
        List<Map> menuList = (List<Map>) role.get("routes");
        for(Map menu:menuList){
            Long menuId;
            if(menu.get("id") instanceof Integer){
                Integer menuIdInt = (Integer) menu.get("id");
                menuId = new Long(menuIdInt);
            }else{
                menuId = (Long) menu.get("id");
            }
            roleMapper.assignMenu(roleId,menuId);
        }
    }

    @Override
    public boolean roleHasMenu(Long rlId, Long mnId) {
        List<AuthSysMenu> menus = this.menuService.findByRoleId(rlId);
        boolean bool = false;
        if(menus != null){
            for(AuthSysMenu mn:menus){
                if(mn.getId() == mnId){
                    bool = true;
                    break;
                }
            }
        }
        return bool;
    }

    @Override
    public List<Long> searchMenuRoleIds(String mnName) {
        return this.roleMapper.selectRolesByMnName(mnName);
    }

    @Override
    public void updateRolePermissions(AuthSysRole role) {
        this.roleMapper.unassignPermssions(role.getRlId());
        if(role.getPermissionList() != null){
            for(AuthSysPermission perm:role.getPermissionList())
            this.roleMapper.assignPermssion(role.getRlId(), perm.getPrmId());
        }
    }

    @Override
    public Result selectRoleList(Map params) {
        Result result = new Result();
        List<Map> roleList = roleMapper.selectRoleList(params);
        //查询角色的路由菜单信息
        for(Map role:roleList){
            List<Long> menuList = roleMapper.selectMenuListByRoleId((Long) role.get("sysRoleId"));
            role.put("routes",menuList);
        }
        result.setBeans(roleList);
        return result;
    }
}
